<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\PayInfo\WxReturnMoneyController;
use App\Models\OnlineRegistration;
use App\Models\OnlineRegistrationOrder;
use App\Models\OnlineRegistrationOrderPay;
use App\Models\OnlineRegistrationOrderRefund;
use App\Models\RegisterVerify;
use App\Validate\OnlineRegistrationValidate;
use Exception;
use Illuminate\Support\Facades\DB;
use SendTemplateSMS;

/**
 * 在线办证控制器
 * Class OnlineRegistration
 * @package app\api\controller
 */
class OnlineRegistrationController extends CommonController
{
    private $validate = null;
    private $model = null;
    private $limit = 99999;


    public function __construct()
    {
        parent::__construct();
        $this->validate = new OnlineRegistrationValidate();
        $this->model = new OnlineRegistration();
    }

    /**
     * 获取动态参数
     * 
     * 配置界面选项，多个用“|”链接     1.头像(弃用) 2.居住地 3.身份证正反面 4.电子邮箱 5.邮政编码 6.座机号码 7.读者职业 8.文化程度 9.工作单位 10.备注  999 是否显示书店（特殊判断）
     */
    public function getDynamicParam()
    {
        $data = $this->model->dynamicParam();
        $data = $data ? explode('|', $data) : [];

        if (config('other.online_registration_is_need_shop_id')) {
            $data[] = '999';
        }
        return $this->returnApi(200, '获取成功', true, $data);
    }


    /**
     * 发送验证码
     * @param tel     电话号码
     * @param key     电话号码+tel_key    后的MD5值     md5(13030303030.tel_key)
     * @param state   类型  在线办证 1
     */
    public function sendVerify()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('send')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $number = get_rnd_number(6); //获取验证码
        $obj = new SendTemplateSMS();
        //选择模板编号
        $tel = $this->request->tel;
        $state = strtoupper($this->request->state);
        $registerVerifyObj = new RegisterVerify();
        //  $template = $registerVerifyObj->getTemplate($state);
        //  $result = $obj->sendTemplateSMS($this->request->tel, array($number, '5分钟'), $template); //手机号码，替换内容数组，模板ID

        //测试环境下，验证码全是6个0
        $result['code'] = '200';
        $number = '000000';

        $expir = strtotime("+5 minutes");
        $expir_time = date('Y-m-d H:i:s', $expir);
        if ($result['code'] == '200') {
            //发送成功之后，先删除之前此电话号码的验证码 + 储蓄验证码
            $registerVerifyObj->addVerify($tel, $number, $expir_time);

            return $this->returnApi(200, '发送成功', true);
        } else {
            return $this->returnApi(202, '验证码发送失败');
        }
    }

    /**
     * 获取证件类型
     */
    public function getCertificateType()
    {
        $res = $this->model->getCertificateType();

        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取在线办证类型
     * @param shop_id 图书馆id
     * @param certificate_type  证件类型  1 为身份证  2 为其他证
     */
    public function getCardType()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('admin_get_card_type')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $certificate_type = request()->input('certificate_type', 1);
        if ($certificate_type == 1) {
            $res = $this->model->getCardType($this->request->shop_id);
        } else {
            $res = $this->model->getCardByFrontOther();
        }

        if ($res) {
            sort($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
    /**
     * 获取在前台线办证类型
     */
    public function getFrontCardType()
    {
        $res = $this->model->getCardByFront();
        if ($res) {
            sort($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 读者证-办证接口
     * @param $certificate_type   证件类型  1 为身份证  2 为其他证
     * @param $shop_id   书店id       选填
     * @param $id_card   身份证        必传
     * @param $username  读者姓名      必传
     * @param $card_type 读者证类型     必传
     * @param $workunit  工作单位
     * @param $province   省
     * @param $city       市
     * @param $district   区
     * @param $address   详细地址
     * @param $zip       邮编
     * @param $phone     电话号码
     * @param $tel       手机号码       必传
     * @param $email     电子邮箱
     * @param $culture   文化程度       必传
     * @param $position  职业           必传
     * @param $remark     备注
     * @param $verify  验证码
     */
    public function registration()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('online_register')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        if ($this->request->certificate_type == 2 && $this->request->card_type != 28) {
            return $this->returnApi(201, '读者证号类型错误');
        }
        if ($this->request->email && !is_email($this->request->email)) {
            return $this->returnApi(201, '邮箱格式不正确');
        }
        if (config('other.online_registration_is_need_shop_id') && empty($this->request->shop_id)) {
            return $this->returnApi(201, '书店id不能为空');
        }


        //判断此身份证是否办过卡
        $libApi = $this->getLibApiObj();
        //判断 身份证 是否在所有一卡通办过证，因为在所有一卡通办过证的，在本馆没办过证的身份证，也办不起，只能办理 “其他” 证
        $id_card_cloud_exist = $libApi->validateIdnoIsExist($this->request->id_card);
        if ($id_card_cloud_exist['code'] == 203) {
            return $this->returnApi(202, $id_card_cloud_exist['msg']);
        }

        $id_card_exist = $libApi->getReaderPageInfoByIdno($this->request->id_card);
        if ($id_card_exist['code'] == 200) {
            return $this->returnApi(202, '此身份证号码已办理过读者证，请勿重复办理！');
        }
        if ($id_card_exist['code'] == 203) {
            return $this->returnApi(202, $id_card_exist['msg']);
        }

        //在一卡通办过证，在本馆未办过证，说明只在其他馆办过，在本馆就只能办理“其他” 证
        if ($id_card_cloud_exist['code'] == 200 && $id_card_exist['code'] == 202 && $this->request->certificate_type == 1) {
            $card_status['msg'] = $this->model->repetitionCertificateMsg;
            return $this->returnApi(202, $card_status['msg']);
        }

        //判读是否在我们本地是否办过证
        $is_exists = OnlineRegistration::where('id_card', $this->request->id_card)->where('is_pay', 2)->first();
        if ($is_exists) {
            return $this->returnApi(202, '此身份证号码已办理过读者证，请勿重复办理！');
        }
        $is_exists = OnlineRegistration::where('id_card', $this->request->id_card)->where('is_pay', 1)->first();
        if ($is_exists) {
            return $this->returnApi(202, '此身份证号码已在线申请过读者证，请到个人中心进行支付！');
        }

        $remark = request()->input('remark', '');
        if (mb_strlen($remark) > 300) {
            return $this->returnApi(202, '备注字数不能超过300字');
        }

        $province = request()->input('province', '');
        $district = request()->input('district', '');
        $city = request()->input('city', '');
        $street = request()->input('street', '');
        $address = request()->input('address', '');
        if ((empty($province) || empty($city) || empty($district) || empty($address)) && !(empty($province) && empty($city) && empty($district) && empty($address))) {
            return $this->returnApi(201, '地址信息填写错误');
        }

        DB::beginTransaction();
        try {
            //获取读者证号
            $reader_id = $this->model->getReaderId($this->request->card_type);
            if (empty($reader_id)) {
                return $this->returnApi(202, '获取读者证号失败');
            }

            OnlineRegistration::where('phone', $this->request->tel)->delete(); //验证成功，删除验证码

            $data['shop_id'] = $this->request->shop_id;
            $data['reader_id'] = $reader_id;
            $data['certificate_type'] = $this->request->certificate_type;
            $data['certificate_num'] = $this->request->certificate_type == 1 ? $this->request->id_card : $this->request->id_card . 'Z';
            $data['id_card'] = $this->request->id_card;
            $data['username'] = $this->request->username;
            $data['card_type'] = $this->request->card_type;
            $data['cash'] = $this->model->getCardByFrontList($this->request->card_type)['cash'];
            $data['tel'] = $this->request->tel;
            $data['birthday'] = get_user_birthday_by_id_card($this->request->id_card);
            $data['sex'] = get_user_sex_by_id_card($this->request->id_card);
            $data['workunit'] = request()->input('workunit', '');
            $data['province'] = $province;
            $data['city'] = $city;
            $data['district'] = $district;
            $data['street'] = $street;
            $data['address'] = $address;
            $data['zip'] = request()->input('zip', '');
            $data['phone'] = request()->input('phone', '');
            $data['email'] = request()->input('email', '');
            $data['culture_id'] = request()->input('culture_id', '');
            $data['culture'] = request()->input('culture', '');
            $data['position_id'] = request()->input('position_id', '');
            $data['position'] = request()->input('position', '');
            $data['is_pay'] = 2;
            $data['source'] = 2;
            $data['pay_way'] = 1;
            $data['status'] = 1; //1 已领取 
            $data['node'] = 1; //是否写入文华系统，默认直接写入
            $data['remark'] = addslashes($remark);
            $data['certificate_manage_id'] = $this->request->manage_id; //办证管理员id
            $this->model->add($data);

            if (config('other.is_validate_lib_api')) {
                $card_status = $libApi->readerIdAdd($data);
                if ($card_status['code'] !== 200) {
                    $msg = mb_substr($card_status['msg'], 0, 36);
                    if ($msg == $this->model->contrastMsg) {
                        $card_status['msg'] = $this->model->repetitionCertificateMsg;
                    }
                    throw  new Exception($card_status['msg']);
                }
            }

            DB::commit();
            return $this->returnApi(200, '读者证办理成功，读者证号为：' . $reader_id, true, [
                'reader_id' => $reader_id, //前台提示
                'password' => str_replace('-', '', $data['birthday'])
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     *（发起方）办证统计列表 （前台在线办证列表）
     * @param shop_id 书店id 默认全部
     * @param keywords_type  检索条件   0、全部  1、读者证号  2、身份证号码 3 姓名 默认 0
     * @param keywords  检索条件
     * @param card_type  类型  默认全部
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param certificate_type		证件类型  0、全部 1 为身份证  2 为其他证
     * @param certificate_manage_id		办证操作人
     * @param status  是否领取  0 全部 1 已领取  2 待领取  3 无需领取
     * @param source		办证来源 1前端 2后台
     * @param node		是否写入成功  1 成功  2 失败
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function sponsorRegistrationList()
    {
        $shop_id = request()->input('shop_id', '');
        $start_time = request()->input('start_time', '');
        $end_time = request()->input('end_time', '');
        $keywords_type = request()->input('keywords_type');
        $keywords = request()->input('keywords', '');
        $settle_state = request()->input('settle_state', '');
        $card_type = request()->input('card_type', '');
        $source = request()->input('source', '');
        $node = request()->input('node', '');
        $status = request()->input('status', '');
        $certificate_type = request()->input('certificate_type', '');
        $certificate_manage_id = request()->input('certificate_manage_id', '');
        $page = intval(request()->input('page', 1)) ?: 1;
        $limit = intval(request()->input('limit', 10)) ?: 10;

        $shop_all_id = $this->getAdminShopIdAll();
        if ((empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) && $source == 2) {
            return $this->returnApi(203, '您无权查看此书店数据'); //无权限访问
        }
        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'settle_state' => $settle_state,
            'card_type' => $card_type,
            'source' => $source,
            'node' => $node,
            'status' => $status,
            'certificate_type' => $certificate_type,
            'certificate_manage_id' => $certificate_manage_id,
            'shop_all_id' => $shop_all_id,
            'page' =>  $page,
            'limit' =>  $limit,
            'select_way' => 1,
        ];

        $res = $this->model->lists($param);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }
        return $this->returnApi(200, '获取成功', true, $res);
    }


    /**
     *（发起方）办证统计数据  （前台在线办证列表）
     * @param shop_id 书店id 默认全部
     * @param keywords_type  检索条件   0、全部  1、读者证号  2、身份证号码 3 姓名 默认 0
     * @param keywords  检索条件
     * @param card_type  类型  默认全部
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param certificate_type		证件类型  0、全部 1 为身份证  2 为其他证
     * @param certificate_manage_id		办证操作人
     * @param status  是否领取  0 全部 1 已领取  2 待领取  3 无需领取
     * @param source		办证来源 1前端 2后台
     * @param node		是否写入成功  1 成功  2 失败
     */
    public function sponsorRegistrationStatistics()
    {
        $shop_id = request()->input('shop_id', '');
        $card_type = request()->input('card_type', '');
        $start_time = request()->input('start_time', '');
        $end_time = request()->input('end_time', '');
        $keywords_type = request()->input('keywords_type');
        $keywords = request()->input('keywords', '');
        $certificate_type = request()->input('certificate_type', '');
        $certificate_manage_id = request()->input('certificate_manage_id', '');
        $source = request()->input('source', '');
        $node = request()->input('node', '');
        $status = request()->input('status', '');

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
            return $this->returnApi(203, '您无权查看此书店数据'); //无权限访问
        }
        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'card_type' => $card_type,
            'source' => $source,
            'node' => $node,
            'status' => $status,
            'certificate_type' => $certificate_type,
            'certificate_manage_id' => $certificate_manage_id,
            'shop_all_id' => $shop_all_id,
            'limit' =>  $this->limit,
            'select_way' => 1,
        ];

        //已结算 总数量
        $param['select_way'] = 4;
        $param['settle_state'] = 1;
        $res['settled_number'] = $this->model->lists($param);
        //结算中 总数量
        $param['settle_state'] = 2;
        $res['settling_number'] = $this->model->lists($param);
        //未结算 总数量
        $param['settle_state'] = 3;
        $res['settlno_number'] = $this->model->lists($param);

        //已结算 总价格
        $param['select_way'] = 3;
        $param['settle_state'] = 1;
        $res['settled_money'] = $this->model->lists($param);
        //结算中 总价格
        $param['settle_state'] = 2;
        $res['settling_money'] = $this->model->lists($param);
        //未结算 总价格
        $param['settle_state'] = 3;
        $res['settlno_money'] = $this->model->lists($param);

        $res['total_number'] = $res['settled_number'] + $res['settling_number'] + $res['settlno_number'];
        $res['total_money'] = $res['settled_money'] + $res['settling_money'] + $res['settlno_money'];


        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     *（确认方）办证统计列表
     * @param shop_id 书店id 默认全部
     * @param keywords_type  检索条件   0、全部  1、读者证号  2、身份证号码 3 姓名 默认 0
     * @param keywords  检索条件
     * @param card_type  类型  默认全部
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param certificate_type		证件类型  0、全部 1 为身份证  2 为其他证
     * @param settle_affirm_manage_id		确认结算操作人
     * @param source		办证来源 1前端 2后台
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function confirmPostageList()
    {
        $shop_id = request()->input('shop_id', '');
        $start_time = request()->input('start_time', '');
        $end_time = request()->input('end_time', '');
        $keywords_type = request()->input('keywords_type');
        $keywords = request()->input('keywords', '');
        $settle_state = request()->input('settle_state', '');
        $card_type = request()->input('card_type', '');
        $certificate_type = request()->input('certificate_type', '');
        $settle_affirm_manage_id = request()->input('settle_affirm_manage_id', '');
        $source = request()->input('source', '');
        $page = intval(request()->input('page', 1)) ?: 1;
        $limit = intval(request()->input('limit', 10)) ?: 10;

        //后台办证才判断图书馆，前台办证无书店概念
        $shop_all_id = [];
        if ($source == 2) {
            $shop_all_id = $this->getAdminShopIdAll();
            if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
                return $this->returnApi(203, '您无权查看此书店数据'); //无权限访问
            }
        }
        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'settle_state' => $settle_state,
            'card_type' => $card_type,
            'source' => $source,
            'certificate_type' => $certificate_type,
            'settle_affirm_manage_id' => $settle_affirm_manage_id,
            'shop_all_id' => $shop_all_id,
            'page' =>  $page,
            'limit' =>  $limit,
            'select_way' => 1,
        ];

        $res = $this->model->lists($param);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }
        return $this->returnApi(200, '获取成功', true, $res);
    }



    /**
     * （确认方） 邮费统计 金额及书籍本数 统计
     * @param shop_id 书店id 默认全部
     * @param keywords_type  检索条件   0、全部  1、读者证号  2、身份证号码 3 姓名 默认 0
     * @param keywords  检索条件
     * @param card_type  类型  默认全部
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param certificate_type		证件类型  0、全部 1 为身份证  2 为其他证
     * @param settle_affirm_manage_id		确认结算操作人
     * @param source		办证来源 1前端 2后台
     */
    public function confirmPostageStatistics()
    {
        $shop_id = request()->input('shop_id', '');
        $card_type = request()->input('card_type', '');
        $start_time = request()->input('start_time', '');
        $end_time = request()->input('end_time', '');
        $keywords_type = request()->input('keywords_type');
        $keywords = request()->input('keywords', '');
        $settle_state = request()->input('settle_state', '');
        $source = request()->input('source', '');
        $certificate_type = request()->input('certificate_type', '');
        $settle_affirm_manage_id = request()->input('settle_affirm_manage_id', '');

        //后台办证才判断图书馆，前台办证无书店概念
        $shop_all_id = [];
        if ($source == 2) {
            $shop_all_id = $this->getAdminShopIdAll();
            if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
                return $this->returnApi(203, '您无权查看此书店数据'); //无权限访问
            }
        }

        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'card_type' => $card_type,
            'source' => $source,
            'settle_state' => $settle_state,
            'certificate_type' => $certificate_type,
            'settle_affirm_manage_id' => $settle_affirm_manage_id,
            'shop_all_id' => $shop_all_id,
            'limit' =>  $this->limit,
            'select_way' => 1,
        ];

        //已结算 总数量
        $param['select_way'] = 4;
        $param['settle_state'] = 1;
        $res['settled_number'] = $this->model->lists($param);
        //结算中 总数量
        $param['settle_state'] = 2;
        $res['settling_number'] = $this->model->lists($param);
        //未结算 总数量
        $param['settle_state'] = 3;
        $res['settlno_number'] = $this->model->lists($param);

        //已结算 总价格
        $param['select_way'] = 3;
        $param['settle_state'] = 1;
        $res['settled_money'] = $this->model->lists($param);
        //结算中 总价格
        $param['settle_state'] = 2;
        $res['settling_money'] = $this->model->lists($param);
        //未结算 总价格
        $param['settle_state'] = 3;
        $res['settlno_money'] = $this->model->lists($param);

        $res['total_number'] = $res['settled_number'] + $res['settling_number'] + $res['settlno_number'];
        $res['total_money'] = $res['settled_money'] + $res['settling_money'] + $res['settlno_money'];


        return $this->returnApi(200, '获取成功', true, $res);
    }


    /**
     * （发起方）标记办证状态为结算中
     * @param ids 多个 , 逗号拼接
     */
    public function sponsorSettleState()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('admin_sponsor_settle_state')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(202, '您无权操作此书店数据'); //无权限访问
        }

        $ids = $this->request->ids;
        $ids = explode(',', $ids);
        $ids = array_unique(array_filter($ids));

        DB::beginTransaction();
        try {
            $this->model->where('settle_state', 3)
                ->whereIn('shop_id', $shop_all_id)
                ->whereIn('id', $ids)
                ->update([
                    'settle_state' => 2,
                    'settle_affirm_time' => date('Y-m-d H:i:s'),
                    'settle_affirm_manage_id' => $this->request->manage_id,
                ]);
            DB::commit();
            return $this->returnApi(200, '操作成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '操作失败');
        }
    }
    /**
     * （确认方） 标记邮费状态为已结算
     * @param ids 多个 , 逗号拼接
     */
    public function confirmSettleState()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('admin_confirm_settle_state')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(202, '您无权操作此书店数据'); //无权限访问
        }

        $ids = $this->request->ids;
        $ids = explode(',', $ids);
        $ids = array_unique(array_filter($ids));
        DB::beginTransaction();
        try {
            $this->model->where('settle_state', 2)
                ->whereIn('shop_id', $shop_all_id)
                ->whereIn('id', $ids)
                ->update([
                    'settle_state' => 1,
                    'settle_sponsor_time' => date('Y-m-d H:i:s'),
                    'settle_sponsor_manage_id' => $this->request->manage_id,
                ]);
            DB::commit();
            return $this->returnApi(200, '操作成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '操作失败');
        }
    }

    /**
     * 领取读者证
     * @param id 读者证id
     */
    public function toReceive()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('admin_to_receive')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;

        DB::beginTransaction();
        try {
            $this->model->where('status', 2)
                ->where('id', $id)
                ->update([
                    'status' => 1,
                    'change_time' => date('Y-m-d H:i:s')
                ]);
            DB::commit();
            return $this->returnApi(200, '操作成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '操作失败');
        }
    }


    /**
     * 获取办证参数
     */
    public function getOnlineParam()
    {
        $libApi = $this->getLibApiObj();
        $param = $libApi->getOnlineReaderCardCreateParam();
        if ($param['code'] == 200) {
            return $this->returnApi(200, '获取成功', true, $param['keywords']);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 写入图书馆系统失败，办证失败，进行退款操作  （用于自动退款失败后手动退款）
     * @param order_id 订单id
     * @param refund_remark 退款备注
     */
    public function refund()
    {
        $order_id = request()->input('order_id');
        $refund_remark = request()->input('refund_remark');
        if (empty($order_id)) {
            return $this->returnApi(201, '订单号不能为空');
        }
        if (empty(trim($refund_remark))) {
            $refund_remark = '办证失败';
        }

        $onlineRegistrationOrderModelObj = new OnlineRegistrationOrder();

        $online_registration_info = OnlineRegistration::where('order_id', $order_id)->first();
        $order_info = $onlineRegistrationOrderModelObj->find($order_id);
        if (empty($order_info)) {
            return $this->returnApi(202, '订单获取失败');
        }
        if (empty($online_registration_info)) {
            return $this->returnApi(202, '获取办证信息失败');
        }
        if ($order_info['is_pay'] == 5) {
            return $this->returnApi(202, '此订单已退款，无需重复操作');
        }
        if ($order_info['is_pay'] != 2) {
            return $this->returnApi(202, '订单异常');
        }

        $refund_no = get_order_id();
        $trade_no = OnlineRegistrationOrderPay::where('order_number', $order_info->order_number)->value('trade_no');  //微信支付订单号
        $wxReturnMoney = new WxReturnMoneyController();
        $return_info = $wxReturnMoney->doRefund($order_info->dis_price, $order_info->dis_price, $refund_no, $trade_no, $order_info->order_number, $refund_remark);

        $onlineRegistrationOrderRefundModel = new OnlineRegistrationOrderRefund();

        $time = date('Y-m-d H:i:s');
        if ($return_info['code'] === 200) {
            //退款成功
            DB::beginTransaction();
            try {
                $onlineRegistrationOrderRefundModel->refund_number = $refund_no;
                $onlineRegistrationOrderRefundModel->refund_id = $return_info['refund_id'];
                $onlineRegistrationOrderRefundModel->refund_time = $time;
                $onlineRegistrationOrderRefundModel->price = $order_info->price;
                $onlineRegistrationOrderRefundModel->payment = 1;
                $onlineRegistrationOrderRefundModel->status = 1;
                $onlineRegistrationOrderRefundModel->manage_id = $this->request->manage_id;
                $onlineRegistrationOrderRefundModel->save();
                //修改订单状态
                $order_info->is_pay = 5;
                $order_info->refund_number = $refund_no;
                $order_info->refund_time = $time;
                $order_info->refund_remark = $this->request->refund_remark;
                $order_info->refund_manage_id = $this->request->manage_id;
                $order_info->save();

                //修改在线办证表
                OnlineRegistration::where('order_id', $order_info['id'])->update(['is_pay' => 5]);

                //添加系统消息
                $this->systemAdd('在线办证：押金已成功退回', $order_info->user_id, $order_info->account_id, 26, $order_id, '押金已成功退回；退回理由: ' . $this->request->refund_remark);

                DB::commit();
                return $this->returnApi(200, '退款成功');
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->returnApi(202, '退款失败');
            }
        } else {
            //添加退款日志
            $onlineRegistrationOrderRefundModel->refund_number = $refund_no;
            $onlineRegistrationOrderRefundModel->refund_time = $time;
            $onlineRegistrationOrderRefundModel->price = $order_info->price;
            $onlineRegistrationOrderRefundModel->payment = 1;
            $onlineRegistrationOrderRefundModel->status = 2;
            $onlineRegistrationOrderRefundModel->manage_id = $this->request->user_id;
            if (isset($return_info['err_code'])) $onlineRegistrationOrderRefundModel->error_code = $return_info['err_code'];

            $onlineRegistrationOrderRefundModel->error_msg = $return_info['msg'];
            $onlineRegistrationOrderRefundModel->save();

            //退款失败
            return $this->returnApi(202, $return_info['msg']);
        }
    }
}
